package com.bodacn.storagescan;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.security.Key;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static com.bodacn.storagescan.DBUtil.replaceBlank;


public class CarRecDetailActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG=this.getClass().getName();
    public static final int MSG_DetailOver = 1001;
    public static final int MSG_PurchaseNo =1002;
    public static final int MSG_CallAGV=1003;
    public static final int MSG_ERROR = 9009;
    ImageButton btn_return;
    TextView txt_titleInv;
    ListView detailList;
    String serviceUrl="http://192.168.10.12/tvservice";
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String curLoginUserNo,curLoginUser,FormType,CustName,curLoginTime;//操作员所属部门等信息;
    JSONArray detailJSON,searchJSON,headJSON=null;
    EditText edt_SupplierName;
    EditText edt_PlateNumer,edt_Driver,edt_PurchaseNo,edt_TrayCode;
    ImageButton btn_Append;
    Button btn_NewTray,btn_ClearTray,btn_SaveTrayCall;

    View contentView;
    LinearLayout templetlisthead;
    TextView tv_pop_title;
    EditText edt_pop_fliter;
    PopupWindow popupWindow;
    LinearLayout mainLinerLayout;
    ListView lv_Detail;
    String selPurchaseNo ="",selSupplierName="";
    String tmpPurchaseNo ="",tmpSupplierName="";
    String trayCarID="";
    //全局变量
    Toast curToast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_carrec_detail);
        InitView();
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curLoginTime=paramBundle.getString("LoginTime");
        CustName=paramBundle.getString("CustName");
        FormType=paramBundle.getString("FormType","UNKNOW");
        selSupplierName =paramBundle.getString("SupplierName","UNKNOW");
        edt_SupplierName.setText(selSupplierName);
        ((TextView)findViewById(R.id.tv_userName)).setText(curLoginUser);
        //初始提醒;
        curToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        //先显示对话框,再调用查询加载
        initPopwindow();
        try {
            detailJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        DetailListAdapter detailListAdapter = new DetailListAdapter(contentView.getContext());
        detailList.setAdapter(detailListAdapter);
    }

    private void InitView(){
        edt_SupplierName=findViewById(R.id.edt_SupplierName);
        edt_PlateNumer=findViewById(R.id.edt_PlateNumer);
        edt_Driver=findViewById(R.id.edt_Driver);
        edt_PurchaseNo=findViewById(R.id.edt_PurchaseNo);
        edt_PurchaseNo.setOnClickListener(this);
        edt_TrayCode=findViewById(R.id.edt_TrayCode);
        edt_TrayCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction()==KeyEvent.ACTION_UP)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                {
                    //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                    // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                    //隐藏键盘
                    //System.out.println(edit_Barcode.getText().toString());
                    hideIM(edt_TrayCode);
                    edt_TrayCode.setText(replaceBlank(edt_TrayCode.getText().toString()));
                    return true;
                }
                return false;
            }
        });
        btn_Append=findViewById(R.id.btn_Append);
        btn_Append.setOnClickListener(this);
        btn_NewTray=findViewById(R.id.btn_NewTray);
        btn_NewTray.setOnClickListener(this);
        btn_ClearTray=findViewById(R.id.btn_ClearTray);
        btn_ClearTray.setOnClickListener(this);
        btn_SaveTrayCall=findViewById(R.id.btn_SaveTrayCall);
        btn_SaveTrayCall.setOnClickListener(this);

        btn_return=findViewById(R.id.btn_return);
        btn_return.setOnClickListener(this);
        txt_titleInv=findViewById(R.id.txt_titleInv);
        detailList=findViewById(R.id.detailList);
        mainLinerLayout=findViewById(R.id.mainLinerLayout);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选疵点返回
        if ((requestCode==2000)&&(resultCode==2001)){
            //获取登陆参数
            Bundle paramBundle = data.getExtras();
            try {
                JSONObject itemObject= new JSONObject(paramBundle.getString("itemObject"));
                System.out.println(itemObject);
                detailJSON.put(itemObject);
                ((BaseAdapter)detailList.getAdapter()).notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void initPopwindow() {
        selPurchaseNo ="";
        contentView = LayoutInflater.from((Context)this).inflate(R.layout.popselect, null);
        popupWindow = new PopupWindow(contentView, -1, -2);
        popupWindow.setFocusable(true);
        contentView.findViewById(R.id.btn_pop_cancel).setOnClickListener(new View.OnClickListener() {
            public void onClick(View param1View) {
                if (popupWindow != null && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        edt_pop_fliter =contentView.findViewById(R.id.edt_pop_fliter);
        tv_pop_title = (TextView)contentView.findViewById(R.id.tv_pop_title);
        lv_Detail = (ListView)contentView.findViewById(R.id.lv_Detail);

        templetlisthead = (LinearLayout)contentView.findViewById(R.id.templetlisthead);
        popupWindow.setBackgroundDrawable((Drawable)new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
    }
    private void showSelectPurchaseNo(){
        try {
            searchJSON=new JSONArray("[]");
            headJSON = new JSONArray("["
                    +"{'TitleName':'StyleNo','TitleText':'款号','TxtSize':16,'TxtWidth':150,'AutoZoom':0,'Align':0,'Color':'Main'},"
                    +"{'TitleName':'PurchaseNo','TitleText':'采购单号','TxtSize':16,'TxtWidth':300,'AutoZoom':0,'Align':0,'Color':'Main'},"
                    +"{'TitleName':'SupplierName','TitleText':'供应商','TxtSize':16,'TxtWidth':300,'AutoZoom':0,'Align':0,'Color':'Main'},"
                    +"{'TitleName':'PurchaseDate','TitleText':'采购日期','TxtSize':16,'TxtWidth':150,'AutoZoom':0,'Align':0,'Color':'Main'}"
                    +"]");
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        tv_pop_title.setText("采购单选择");
        contentView.findViewById(R.id.btn_pop_ok).setOnClickListener(new View.OnClickListener() {
            public void onClick(View param1View) {
                if (tmpPurchaseNo.length() > 0){
                    selPurchaseNo=tmpPurchaseNo;
                    edt_PurchaseNo.setText(selPurchaseNo);
                    selSupplierName=tmpSupplierName;
                    edt_SupplierName.setText(selSupplierName);
                    hideIM(param1View);
                    if (popupWindow != null && popupWindow.isShowing()) popupWindow.dismiss();
                } else {
                    curToast.setText("请选择需要选择的内容！");
                    curToast.show();
                }
            }
        });
        contentView.findViewById(R.id.linear_pop_search).setVisibility(View.VISIBLE);
        contentView.findViewById(R.id.btn_pop_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchSelectPurchaseNo(selSupplierName,edt_pop_fliter.getText().toString());
                hideIM(v);
            }
        });
        CreateListHead();
        lv_Detail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> param1AdapterView, View view, int postion, long param1Long) {
                try {
                    view.setSelected(true);
                    if (searchJSON.optJSONObject(postion).has("PurchaseNo") == true) {
                        tmpPurchaseNo = searchJSON.optJSONObject(postion).getString("PurchaseNo");
                        tmpSupplierName = searchJSON.optJSONObject(postion).getString("SupplierName");
                    }

                } catch (JSONException jSONException) {
                    jSONException.printStackTrace();
                }
            }
        });
        //控制屏幕宽度
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        popupWindow.setWidth(dm.widthPixels);
        popupWindow.setHeight(dm.heightPixels-120);
        popupWindow.showAtLocation(mainLinerLayout, Gravity.BOTTOM,0,0);
        //加载默认的历史合约;
        SearchSelectPurchaseNo(selSupplierName,"");
    }



    private void SaveData(final String paramSupplierName, final String paramPlateNumer, final String paramDriver,
                          final String paramPurchaseNo, final String paramTrayCarID, final String paramTrayCode) {
        JSONArray jsonArray = detailJSON;
        if (jsonArray != null) {
            if (jsonArray.length() == 0)
                return;
            System.out.println("curLoginUserNo:"+curLoginUserNo+" curLoginUser:"+curLoginUser);
            //线程直接保存不经过WebService;
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    //将数据读到JSONArray;
                    try {
                        System.out.println("A");
                        String trayRecMaID="",styleNo="",materialNo="",diameter="",
                                materialName="",model="",doorWidth="",bowlNo="",blowNoInside="",squareWeight="",uint="",number="",uintAssist="",numberAssist="";
                        //清空临时数据
                        DBUtil.getSQLConnection().createStatement().
                                executeUpdate("Delete from scan_tray_rec_car where trayCarID='"+paramTrayCarID+"'");
                        System.out.println("Delete Over");
                        PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement("Insert into scan_tray_rec_ma(" +
                                "trayRecMaID,trayCarID,styleNo,materialNo,materialName,model,doorWidth,bowlNo,blowNoInside,squareWeight," +
                                "diameter,uint,number,uintAssist,numberAssist) " +
                                "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                        for (int i=0;i<detailJSON.length();i++)
                        {
                            if (detailJSON.optJSONObject(i).has("trayRecMaID"))
                                trayRecMaID=detailJSON.optJSONObject(i).getString("trayRecMaID");
                            if (detailJSON.optJSONObject(i).has("styleNo"))
                                styleNo=detailJSON.optJSONObject(i).getString("styleNo");
                            if (detailJSON.optJSONObject(i).has("materialNo"))
                                materialNo=detailJSON.optJSONObject(i).getString("materialNo");
                            if (detailJSON.optJSONObject(i).has("materialName"))
                                materialName=detailJSON.optJSONObject(i).getString("materialName");
                            if (detailJSON.optJSONObject(i).has("model"))
                                model=detailJSON.optJSONObject(i).getString("model");
                            if (detailJSON.optJSONObject(i).has("doorWidth"))
                                doorWidth=detailJSON.optJSONObject(i).getString("doorWidth");
                            if (detailJSON.optJSONObject(i).has("bowlNo"))
                                bowlNo=detailJSON.optJSONObject(i).getString("bowlNo");
                            if (detailJSON.optJSONObject(i).has("blowNoInside"))
                                blowNoInside=detailJSON.optJSONObject(i).getString("blowNoInside");
                            if (detailJSON.optJSONObject(i).has("squareWeight"))
                                squareWeight=detailJSON.optJSONObject(i).getString("squareWeight");
                            if (detailJSON.optJSONObject(i).has("diameter"))
                                diameter=detailJSON.optJSONObject(i).getString("diameter");
                            if (detailJSON.optJSONObject(i).has("uint"))
                                uint=detailJSON.optJSONObject(i).getString("uint");
                            if (detailJSON.optJSONObject(i).has("number"))
                                number=detailJSON.optJSONObject(i).getString("number");
                            if (detailJSON.optJSONObject(i).has("uintAssist"))
                                uintAssist=detailJSON.optJSONObject(i).getString("numberAssist");
                            if (detailJSON.optJSONObject(i).has("numberAssist"))
                                numberAssist=detailJSON.optJSONObject(i).getString("numberAssist");
                            if (trayRecMaID.length()==0) trayRecMaID=java.util.UUID.randomUUID().toString().toUpperCase();
                            pstmt.setString(1, trayRecMaID);
                            pstmt.setString(2, paramTrayCarID);
                            pstmt.setString(3, styleNo);
                            pstmt.setString(4, materialNo);
                            pstmt.setString(5, materialName);
                            pstmt.setString(6, model);
                            pstmt.setString(7, doorWidth);
                            pstmt.setString(8, bowlNo);
                            pstmt.setString(9, blowNoInside);
                            pstmt.setString(10, squareWeight);
                            pstmt.setString(11, diameter);
                            pstmt.setString(12, uint);
                            pstmt.setString(13, number);
                            pstmt.setString(14, uintAssist);
                            pstmt.setString(15, numberAssist);
                            pstmt.executeUpdate();
                        }
                        pstmt.close();
                        pstmt = DBUtil.getSQLConnection().prepareStatement("Insert into scan_tray_rec_car(" +
                                "trayCarID,trayCarDate,trayCarTime,trayCode," +
                                "supplierName,PurchaseNo,driver,plateNumer,operatorNo,operator,updateTime) " +
                                "values(?,cast(getdate() as Date),getdate(),?,?,?,?,?,?,?,getdate())");
                        pstmt.setString(1, paramTrayCarID);
                        pstmt.setString(2, paramTrayCode);
                        pstmt.setString(3, paramSupplierName);
                        pstmt.setString(4, paramPurchaseNo);
                        pstmt.setString(5, paramDriver);
                        pstmt.setString(6, paramPlateNumer);
                        pstmt.setString(7, curLoginUserNo);
                        pstmt.setString(8, curLoginUser);
                        pstmt.executeUpdate();
                        pstmt.close();
                        String SqlComm = "Exec scan_trayRec_saveTrans @OperType='SaveTrans',@TrayCarID='" + paramTrayCarID + "'";
                        ReadSQLData(SqlComm);
                        return;
                    }
                    catch (SQLException | JSONException ex) {
                        ex.printStackTrace();
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERROR;
                        Bundle bundle=new Bundle();
                        bundle.putString("HintInfo","保存数据出错!"+ex.getMessage());
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                }
            };
            new Thread(run).start();
        }
    }
    //dp 转换成px
    public int dp2px(float dp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    //过滤订单
    private void SearchSelectPurchaseNo(String paramSupplierName,String paramPurchaseNo) {
        //执行SQL过程
        String SqlComm="Exec App_SelectGetData @OperType='PurchaseNo',@SupplierName='" +paramSupplierName+"',@PurchaseNo='"+paramPurchaseNo+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }


    //创建列;
    private void CreateListHead() {
        System.out.println("CreateListHead()");
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        System.out.println("CreateListHead()"+i);
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(this);
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if (StrPenColor.indexOf("#")==0){
            PenColor=Color.parseColor(StrPenColor);
        }else {
            if (isNumeric(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
                if (StrPenColor.equals("Main") == true)
                    PenColor = getResources().getColor(R.color.text_main);
            }
        }
        return PenColor;
    }

    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return searchJSON!=null?searchJSON.length():0;
        }
        @Override
        public Object getItem(int position) {
            try {
                if (searchJSON!=null&&position<searchJSON.length())
                    return searchJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.popselect_item, null, false);
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,dp2px(45)));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (searchJSON!=null && curPosition<searchJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (searchJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = searchJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (searchJSON.optJSONObject(curPosition).has(TitleName)==true)
                                    tmpValue= searchJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } else{
                System.out.println("searchJSON is null");
            }
            return view;
        }
    }

    /*
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                String tmpValue;
                Bundle bundle=msg.getData();
                //任意消息来均置焦点
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_DetailOver:
                        if (detailJSON!=null){
                            DetailListAdapter detailListAdapter = new DetailListAdapter(contentView.getContext());
                            detailList.setAdapter(detailListAdapter);
                        }
                        break;
                    case MSG_PurchaseNo:
                        System.out.println("headJSON:"+headJSON);
                        if (searchJSON!=null) {
                            SelectTempletListAdapter selectTempletListAdapter = new SelectTempletListAdapter(contentView.getContext());
                            lv_Detail.setAdapter(selectTempletListAdapter);
                        } else System.out.println("searchJSON:isnull");
                        break;
                    case MSG_CallAGV:
                        String callTitle=bundle.getString("CallTitle","满托呼叫AGV");
                        String trayCode=bundle.getString("TrayCode",edt_TrayCode.getText().toString());
                        Func_CallAgv(FormType,callTitle,trayCode);
                        break;
                    case MSG_ERROR:
                        String HintInfo=bundle.getString("HintInfo");
                        curToast.setText(HintInfo);
                        curToast.show();
                        break;
                    default:
                        break;
                }
            }
        }
    };

    @Override
    public void onClick(View view) {
        hideIM(view);
        switch (view.getId()){
            case R.id.btn_Query:
                QueryData();
                break;
            case R.id.edt_PurchaseNo:
                showSelectPurchaseNo();
                break;
            case R.id.btn_Append:
                if (edt_PurchaseNo.getText().toString().length()>0)
                    Func_AppendDetail(FormType,edt_PurchaseNo.getText().toString());
                else {
                    curToast.setText("请选择采购单号！");
                    curToast.show();
                }
                break;
            case R.id.btn_NewTray:
                AlertDialog alertDialog = new AlertDialog.Builder(this)
                        .setTitle(getString(R.string.SystemHint)).setMessage("您确定要开始装新托？")
                        .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                hideIM(edt_PurchaseNo);
                                try {
                                    detailJSON=new JSONArray("[]");
                                    DetailListAdapter detailListAdapter = new DetailListAdapter(contentView.getContext());
                                    detailList.setAdapter(detailListAdapter);
                                    edt_TrayCode.setText("");
                                    trayCarID=java.util.UUID.randomUUID().toString().toUpperCase();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                return;
                            }
                        }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                break;
            case R.id.btn_ClearTray:
                try {
                    detailJSON=new JSONArray("[]");
                    DetailListAdapter detailListAdapter = new DetailListAdapter(contentView.getContext());
                    detailList.setAdapter(detailListAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case  R.id.btn_SaveTrayCall:
                if (edt_TrayCode.getText().length()==0||detailJSON==null||detailJSON.length()==0){
                    curToast.setText("请扫描托盘号及录入装托明细！");
                    curToast.show();
                    return;
                }
                AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                        .setTitle(getString(R.string.SystemHint)).setMessage("您确定要保存托盘数据吗？")
                        .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                hideIM(edt_PurchaseNo);
                                SaveDataCallAGV();
                                return;
                            }
                        }).create(); // 创建对话框
                alertDialog1.show(); // 显示对话框

                break;
            case R.id.btn_return:
                finish();
                break;
            default:
                break;
        }
    }

    private void SaveDataCallAGV() {

        if (edt_TrayCode.getText().length()>0&&detailJSON!=null&&detailJSON.length()>0){
            if (trayCarID.length()==0) trayCarID=java.util.UUID.randomUUID().toString().toUpperCase();
            SaveData(edt_SupplierName.getText().toString(),edt_PlateNumer.getText().toString(),
                    edt_Driver.getText().toString(),edt_PurchaseNo.getText().toString(),
                    trayCarID,edt_TrayCode.getText().toString());
        } else {
            curToast.setText("请扫描托盘号！");
            curToast.show();
        }
    }

    //调用功能A
    private void Func_AppendDetail(String paramFormType, String paramPurchaseNo) {
        //跳转前关闭键盘
        Intent tmpctivity  = new Intent(this, CarRecEditActivity.class);
        //简单参数通过Intent的Extras传递;
        Bundle paramBundle = new Bundle();
        paramBundle.putString("LoginUserNo", curLoginUserNo);
        paramBundle.putString("LoginUser", curLoginUser);
        paramBundle.putString("LoginTime", curLoginTime);
        paramBundle.putString("serviceUrl", serviceUrl);
        paramBundle.putString("serviceUrlExt", serviceUrlExt);
        paramBundle.putString("FormType", paramFormType);
        paramBundle.putString("PurchaseNo", paramPurchaseNo);
        paramBundle.putString("SupplierName", selSupplierName);
        paramBundle.putString("Caption", "托盘明细输入");
        tmpctivity.putExtras(paramBundle);
        //启动主界面;
        startActivityForResult(tmpctivity,2000);
    }

    //调用功能A
    private void Func_CallAgv(String paramFormType, String paramCallTitle,String paramTrayCode) {
        //跳转前关闭键盘
        Intent tmpctivity  = new Intent(this, CallAgvActivity.class);
        //简单参数通过Intent的Extras传递;
        Bundle paramBundle = new Bundle();
        paramBundle.putString("LoginUserNo", curLoginUserNo);
        paramBundle.putString("LoginUser", curLoginUser);
        paramBundle.putString("LoginTime", curLoginTime);
        paramBundle.putString("FormType", paramFormType);
        paramBundle.putString("CallTitle", paramCallTitle);
        paramBundle.putString("TrayCode", paramTrayCode);
        paramBundle.putString("CallFunc","MoveFull;");
        paramBundle.putString("Caption", "收货处理");
        tmpctivity.putExtras(paramBundle);
        //启动主界面;
        startActivity(tmpctivity);
    }
    //登陆校验;
    private void QueryData(){
        try {
            detailJSON=new JSONArray("[]");
            //显示预排单;
            final DetailListAdapter detailListAdapter = new DetailListAdapter(this);
            detailList.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String SupplierName=((EditText)findViewById(R.id.edt_SupplierName)).getText().toString();
        String StartDate=((EditText)findViewById(R.id.edt_StartDate)).getText().toString();
        String EndDate=((EditText)findViewById(R.id.edt_EndDate)).getText().toString();
        //执行SQL过程
        String SqlComm = "Exec App_QueryCarRec @OperType='Detail',@UserNo='" + curLoginUserNo
                + "',@SupplierName='"+SupplierName+ "',@StartDate='"+StartDate+ "',@EndDate='"+EndDate+"'";
        ReadSQLData(SqlComm);
    }


    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return  detailJSON!=null?detailJSON.length():0;
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.activity_carrec_detailitem, null, false);
            int pullVatListWidth=parent.getWidth();
            int backcolor = getResources().getColor(R.color.transparent);
            //变换背景色
            if (position%2==1) {
                backcolor=getResources().getColor(R.color.listContentColor);
            }
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(45)));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (detailJSON.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = detailJSON.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.tv_StyleNo);// 显示文字
                if (detailJSON.optJSONObject(position).has("styleNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("styleNo").toString());
                tv.setTextColor(color);
                tv.setBackgroundColor(backcolor);
                tv = (TextView) convertView.findViewById(R.id.tv_MaterialName);// 显示文字
                if (detailJSON.optJSONObject(position).has("materialName")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("materialName").toString());
                tv.setTextColor(color);
                tv.setBackgroundColor(backcolor);
                tv = (TextView) convertView.findViewById(R.id.tv_Model);// 显示文字
                if (detailJSON.optJSONObject(position).has("model")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("model").toString());
                tv.setTextColor(color);
                tv.setBackgroundColor(backcolor);
                tv = (TextView) convertView.findViewById(R.id.tv_BowlNo);// 显示文字
                if (detailJSON.optJSONObject(position).has("bowlNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("bowlNo").toString());
                tv.setTextColor(color);
                tv.setBackgroundColor(backcolor);
                tv = (TextView) convertView.findViewById(R.id.tv_DoorWidth);// 显示文字
                if (detailJSON.optJSONObject(position).has("doorWidth")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("doorWidth").toString());
                tv.setTextColor(color);
                tv.setBackgroundColor(backcolor);
                tv = (TextView) convertView.findViewById(R.id.tv_Diameter);// 显示文字
                if (detailJSON.optJSONObject(position).has("diameter")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("diameter").toString());
                tv.setTextColor(color);
                tv.setBackgroundColor(backcolor);
                tv = (TextView) convertView.findViewById(R.id.tv_Number);// 显示文字
                if (detailJSON.optJSONObject(position).has("number")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("number").toString());
                tv.setTextColor(color);
                tv.setBackgroundColor(backcolor);
                tv = (TextView) convertView.findViewById(R.id.tv_Uint);// 显示文字
                if (detailJSON.optJSONObject(position).has("uint")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("uint").toString());
                tv.setTextColor(color);
                tv.setBackgroundColor(backcolor);
                tv = (TextView) convertView.findViewById(R.id.tv_NumberAssist);// 显示文字
                if (detailJSON.optJSONObject(position).has("numberAssist")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("numberAssist").toString());
                tv.setTextColor(color);
                tv.setBackgroundColor(backcolor);
                tv = (TextView) convertView.findViewById(R.id.tv_UintAssist);// 显示文字
                if (detailJSON.optJSONObject(position).has("uintAssist")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("uintAssist").toString());
                tv.setTextColor(color);
                tv.setBackgroundColor(backcolor);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    String OperType = "";
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType = jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE"))
                            OperType = jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.equals("Detail") == true) {
                            detailJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_DetailOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OperType.equals("PurchaseNo") == true) {
                            searchJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_PurchaseNo;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OperType.equals("SaveTrans") == true) {
                            if (jsonArray.optJSONObject(0).has("CallAgv")) {
                                if (jsonArray.optJSONObject(0).getString("CallAgv").equals("Y")) {
                                    //刷新界面;
                                    Message msg = new Message();
                                    Bundle bundle = new Bundle();
                                    if (jsonArray.optJSONObject(0).has("CallTitle"))
                                        bundle.putString("CallTitle", jsonArray.optJSONObject(0).getString("CallTitle"));
                                    if (jsonArray.optJSONObject(0).has("TrayCode"))
                                        bundle.putString("TrayCode", jsonArray.optJSONObject(0).getString("TrayCode"));
                                    msg.what = MSG_CallAGV;
                                    msg.setData(bundle);
                                    fragmentHandler.removeMessages(msg.what);
                                    fragmentHandler.sendMessage(msg);
                                }
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("HintInfo", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            fragmentHandler.removeMessages(errmsg.what);
                            fragmentHandler.sendMessage(errmsg);
                        }
                    } else {
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("HintInfo", "未返回任何数据!");
                        errmsg.what = MSG_ERROR;
                        errmsg.setData(bundle);
                        fragmentHandler.removeMessages(errmsg.what);
                        fragmentHandler.sendMessage(errmsg);
                    }
                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("HintInfo", e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    fragmentHandler.removeMessages(errmsg.what);
                    fragmentHandler.sendMessage(errmsg);
                }
            }
        };
        new Thread(run).start();

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
